import app_run_time
import logging
import mysql.connector
from mysql.connector import errorcode
import config_default
import time


try:
	connect=mysql.connector.connect(**config_default.configs['db'])
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    logging.error("Something is wrong with your user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    logging.error("Database does not exist")
  else:
    logging.error(err)

# 查询 key对应的脚本值
def select_filter_script_value(key):
	cursor=connect.cursor()
	sql="select trigger_value,monitor_id from filter_script_config where name = %s"
	cursor.execute(sql,(key,))
	val = cursor.fetchone()
	logging.debug("sql <- %s" % cursor.statement)
	logging.debug("result -> key = %s, val = %s" % (key, val))
	cursor.close()
	return val

def select_lt_value_cnt(key, val):
	cursor=connect.cursor()
	sql="select count(*) from filter_script_config where name like %s and trigger_value < %s"
	cursor.execute(sql,(key, val))
	result=cursor.fetchone()
	logging.debug("sql <- %s" % cursor.statement)
	logging.debug("result -> key = %s, val = %s, count = %s" % (key, val, result))
	cursor.close()
	return result[0] if result else 0

def update_script_value(key, val):
	cursor=connect.cursor()
	sql="update filter_script_config set trigger_value='%s' where name = %s"
	cursor.execute(sql, (val, key))
	connect.commit()
	result=cursor.rowcount
	logging.debug("sql <- %s" % cursor.statement)
	logging.debug("result -> rowcount = %d" % result)
	cursor.close()
	return result

def close_db():
	logging.info('close mysql db!!')
	try:
		if connect:
			connect.close()
	except BaseException as e:
		logging.error(e)


app_run_time.add_app_exit_fun(close_db)


if __name__ == '__main__':
	app_run_time.app_start()
	val, monitor =select_filter_script_value(r'内蒙电信-1-100G')
	logging.debug('type %s, val %s' % (type(val), val))
	cnt=select_lt_value_cnt(r'内蒙电信-%port', 319500000000)
	logging.debug('type %s, cnt %s' % (type(cnt), cnt))
	app_run_time.app_exit_befor()
